// pages/xyz-setting/index.js
import {
  _get,
  update
} from '../../api/setting';
import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import {
  useDialog
} from '../../miniprogram_npm/miniprogram-vc-components/dialog/useDialog';
let dialog;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dataSource: []
  },
  onAdd() {
    const {
      dataSource
    } = this.data;
    dataSource.push({
      key: {
        min: '',
        max: ''
      },
      value: {
        x: '',
        y: '',
        z: ''
      }
    })
    this.setData({
      dataSource
    })
  },
  onChange(event) {
    const {
      params,
      value
    } = event.detail,
      [index, key, detail] = [...params], {
        dataSource
      } = this.data;
    dataSource[index][key][detail] = value;
    this.setData({
      dataSource
    })
  },
  fetchData() {
    _get({
      settingKey: 'XYZ_VALUE_SETTINGS'
    }, res => {
      this.setData({
        dataSource: res.settingData.map(it => {
          return {
            ...it,
            key: JSON.parse(it.key),
            value: JSON.parse(it.value)
          }
        })
      })
    })
  },
  onSubmit() {
    update({
      settingKey: 'XYZ_VALUE_SETTINGS',
      settingData: this.data.dataSource.map(it => {
        return {
          ...it,
          key: JSON.stringify(it.key),
          value: JSON.stringify(it.value)
        }
      })
    }, () => {
      Notify({
        type: 'success',
        message: '已保存'
      });
    })
  },
  onRemove(event) {
    const dialogInstance = dialog.init({
      title: "",
      content: "确定要移除此配置吗？",
      icon: "icon-warning",
      showCancel: true,
      mask: true
    }, () => {
      const {
        dataSource
      } = this.data;
      const {
        index
      } = event.currentTarget.dataset;
      dataSource.splice(index, 1);
      this.setData({
        dataSource
      })
      dialogInstance.close();
    },()=>  dialogInstance.close())
    dialogInstance.open();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.fetchData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    dialog = useDialog('#dialog', this);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})